package com.gongpingjialoan.activity.tool;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.activity.main.MainActivity;
import com.gongpingjialoan.bean.Monitor;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.utility.StepMonitor;

import org.json.JSONObject;

/**
 * Created by Administrator on 2016/11/4.
 */
public class WebViewActivity extends BaseActivity {

    private TextView title_txt;

    private String from;

    private WebView webView;
    private String content;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.web_main);
        title_txt = (TextView) findViewById(R.id.top_title);

        webView = (WebView) findViewById(R.id.web_view);
        webView.setDownloadListener(new MyWebViewDownLoadListener());
        WebSettings webSettings = webView.getSettings();
        // 是否允许在webview中执行javascript
        webSettings.setJavaScriptEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        String ua = webView.getSettings().getUserAgentString() + " gpjc-android";
        webSettings.setUserAgentString(ua);
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webView.setWebViewClient(new MyWebViewClient());
        webView.setOnKeyListener(backListener);
        Bundle bundle = getIntent().getExtras();
        final String url = bundle.getString("url", "");
        from = bundle.getString("from", "");
        content = bundle.getString("content", "");
        if (TextUtils.isEmpty(content)){
            title_txt.setText("车源详情");
        }else if("webViewTitle".equals(content)){
        } else{
            title_txt.setText(content);
        }

        if ("post".equals(bundle.getString("loadType"))) {
            final String order_id = bundle.getString("order_id");
            final String user_id = bundle.getString("user_id");
            final String vehicle_value = bundle.getString("vehicle_value");
            final String access_ip = bundle.getString("access_ip");
            final int source = bundle.getInt("source");
            final String city = bundle.getString("city");
            final String postUrl = "http://admin.eflashloan.com/app/equity/personMark";
            ((ImageView) backV).setImageDrawable(getResources().getDrawable(R.drawable.umeng_update_close_bg_normal));
            NetDataJson netDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {

                @Override
                public void onDataJsonError(String errorMessage) {
                    webView.loadUrl(url);
                }

                @Override
                public void onDataJsonUpdate(JSONObject json) {
                    webView.loadUrl(url);
                }
            });
            netDataJson.addParam("order_id", order_id);
            netDataJson.addParam("vehicle_value", vehicle_value);
            netDataJson.addParam("access_ip", access_ip);
            netDataJson.addParam("source", source);
            netDataJson.addParam("user_id", user_id);
            netDataJson.addParam("city", city);
            netDataJson.setUrl(postUrl);
            netDataJson.setUseOtherDomain(true);
            netDataJson.request("post");
        } else {
            webView.loadUrl(url);
        }


        //type不为空代表闪贷
        String type = getIntent().getStringExtra("type");
        if (TextUtils.isEmpty(type)) {
            if ("车抵贷".equals(content)) {
                StepMonitor.getInstance().addMonitor(new Monitor("enter", "eval_carMortgageLoan", System.currentTimeMillis(), 1f));

            } else if ("买车贷款".equals(content)) {
                StepMonitor.getInstance().addMonitor(new Monitor("enter", "eval_loanService", System.currentTimeMillis(), 1f));

            } else if ("检测验车".equals(content)) {
                StepMonitor.getInstance().addMonitor(new Monitor("enter", "eval_validationService", System.currentTimeMillis(), 1f));

            }
        } else {
            StepMonitor.getInstance().addMonitor(new Monitor("enter", type, System.currentTimeMillis(), 1f));
        }


    }


    private class MyWebViewDownLoadListener implements DownloadListener {

        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                                    long contentLength) {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        webView.loadUrl("");
        if ("bannar".equals(from)) {
            if (MainActivity.main != null && MainActivity.main.assessmentFragment.isAdded()) {
                MainActivity.main.assessmentFragment.startPlay();
            }
        }
    }

    private View.OnKeyListener backListener = new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
                webView.goBack(); // goBack()表示返回WebView的上一页面
                return true;
            }
            return false;
        }
    };

    class MyWebViewClient extends WebViewClient {
        @Override
        public void onPageFinished(WebView view, String url) {

            hidenProgressDialog();
            if("webViewTitle".equals(content)){
                title_txt.setText(webView.getTitle());
            }
            // 结束
            super.onPageFinished(view, url);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            showProgressDialog("加载中..");
            // 开始
            super.onPageStarted(view, url, favicon);

        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.contains("tel:")) {
                String phone = getPhoneNumber(url);
                if (TextUtils.isEmpty(phone)) {
                    return false;
                } else {
                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone));
                    startActivity(intent);
                    return true;
                }
            } else if (url.contains("gobacktohome")) {
                finish();
                return true;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }

    }


    private String getPhoneNumber(String url) {
        String phones[] = url.split(":");
        if (phones.length == 2) {
            return phones[1];
        }
        return "";
    }


    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            finish();
        }
        super.onBackPressed();
    }
}
